package com.irdstudio.bsp.executor.core.plugin.migrate.dao;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.*;
import java.util.*;

/**
 * 数据表操作类-[表名: 流程节点信息(bpm_node_info)]
 * 通过JDBC实现基本的数据表操作(CRUD)
 */
public class MigrationtabledataUtilDao {

	private static final Logger logger = LoggerFactory.getLogger(MigrationtabledataUtilDao.class);
	/* 连接对象 */
	Connection conn = null;

	public MigrationtabledataUtilDao(Connection conn){
		this.conn = conn;
	}

	/**
	 * 数据表插入or修改or删除通方法
	 * @param sql
	 * @return int
	 * @throws SQLException
	 */
	public boolean addorupdateordeltable(String sql)
			throws SQLException {
		PreparedStatement ps = null;
		boolean result=true;
		try {
			ps = conn.prepareStatement(sql);
			ps.executeUpdate();
		} catch (SQLException e) {
			throw new SQLException("inserttable	ys is Wrong!"
					+ e.getMessage());
		} finally {
			close(null, null, ps);
		}
		return result;
	}
	/**
	 * 数据表按参数变量插入数据实现
	 * @param sql,targetlist(参数)
	 * @return int
	 * @throws SQLException
	 */
	public boolean datamigration(String sql,List<Map> targetlist)
			throws SQLException {
		PreparedStatement ps = null;
		boolean result=true;
		try {
			ps = conn.prepareStatement(sql);
			for (Map map: targetlist) {
				try {
					int cuont=1;
					for(Object key : map.keySet()){
						String value = map.get(key).toString();
						System.out.println(key+" "+value);
						ps.setString(cuont, value);
						cuont++;
					}
					ps.addBatch();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			ps.executeBatch();
		} catch (SQLException e) {
			result = false;
			throw new SQLException("datamigration is Wrong!"
					+ e.getMessage());
		} finally {
			close(null, null, ps);
		}
		return result;
	}
	/**
	 * sql查询表数据
	 * @param sql
	 * @return List<Map>
	 * @throws SQLException
	 */
	public List<Map> selecttablelist(String sql)
			throws SQLException {
		PreparedStatement ps = null;
		ResultSet rs = null;
		List<Map> result=new ArrayList<>();
		try {
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			ResultSetMetaData rsmd = rs.getMetaData();
			int columncount = rsmd.getColumnCount();
			while  (rs.next()) {
				Map map=new LinkedHashMap();
				for (int i = 0; i < columncount; i++) {
					String key = rsmd.getColumnLabel(i+1);
					String value = rs.getString(key);
					map.put(key, value);
				}
				result.add(map);
			}
		} catch (SQLException e) {
			throw new SQLException("selectyblist is Wrong!"
					+ e.getMessage());
		} finally {
			close(rs, null, ps);
		}
		return result;
	}
	/**
	 * 关闭资源
	 * @param theRs
	 * @param theStmt
	 * @param thePs
	 */
	protected void close(ResultSet theRs, Statement theStmt,
			PreparedStatement thePs) {
		try {
			if (theRs != null)
				theRs.close();
			if (theStmt != null)
				theStmt.close();
			if (thePs != null)
				thePs.close();
		} catch (SQLException e) {
			logger.error(e.getMessage());
		}
	}

}
